package com.china08.yxyapi.service.sws.sws.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.db.sws.SwsSettingDomains;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.entity.mg.sws.SwsArticleForDailyAnalyze;
import com.china08.yxyapi.entity.mg.sws.SwsPvForDailyAnalyze;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.db.SwsSettingDomainsRepository;
import com.china08.yxyapi.service.sws.sws.SwsWebsiteStatisticsMG;
import com.china08.yxyapi.util.DateUtils;
import com.china08.yxyapi.util.SendEmailUtil;

@Service
public class SwsWebsiteStatisticsMGImpl implements SwsWebsiteStatisticsMG {

    private static final Logger LOGGER = Logger.getLogger(SwsWebsiteStatisticsMGImpl.class);

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private SwsSectionRepository swsSectionRepository;

    @Autowired
    SwsSettingDomainsRepository domainsRepository;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 为了补全开通网站的学校数量(total)
     * 
     * @throws ParseException
     */
    @Override
    public void getKaiTongSchoolTotal(Integer date) throws ParseException {
        Integer dateInteger = DateUtils.formatDate4(DateUtils.getBeforeDay(DateUtils.formatStrDate4(date)));
        // 获取所有有网站域名的学校
        List<SwsSettingDomains> domainsList = domainsRepository.findByDomainNameIsNotNull();
        // 去掉重复的数据:久平台一个学校可以设置多个域名
        Set<String> set = new HashSet<String>();
        for (SwsSettingDomains domains : domainsList) {
            String schoolId = domains.getSchoolId();
            String webUrl = domains.getDomainName();

            // schoolId不能为空
            if (StringUtils.isNotBlank(schoolId) && !"null".equals(schoolId)) {
                // 网站域名不能为空
                if (StringUtils.isNotBlank(webUrl) && !"null".equals(webUrl)) {
                    set.add(schoolId);
                }
            }
        }
        List<SchoolModel> schoolModelLst = new ArrayList<SchoolModel>();
        SchoolModel schoolModel = null;
        for (String schoolStr : set) {
            schoolModel = new SchoolModel();
            schoolModel.schoolId = schoolStr;
            schoolModel.date = dateInteger;
            schoolModelLst.add(schoolModel);
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("schoolList", schoolModelLst);
            map.put("dateTime", dateInteger);
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
            String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/sws/schoolIdList/total/buquan/",
                    formEntity, String.class);
            if (result.contains("success")) {
                LOGGER.info("SwsWebsiteStatisticsMGImpl.getKaiTongSchoolTotal():1.补全开通网站的学校数量(total)  成功");
                LOGGER.info("*************************************网站统计结束SwsWebsiteStatisticsMGImpl******************");
            }
        } catch (Exception e) {
            String to = "1179032010@qq.com";
            String header = "补全开通网站的学校数量(total) 报错";
            String text = "SwsWebsiteStatisticsMGImpl.getKaiTongSchoolTotal()：1." + e.getMessage();
            // ## 发送邮件
            SendEmailUtil.sendEmailValidate(to, null, header, text);
            LOGGER.info("错误日志1******:" + e.getMessage());
        }
    }

    /**
     * 为了补全开通网站的学校数量(month)
     * 
     * @throws ParseException
     */
    @Override
    public void getKaiTongSchoolMonth(Integer date) throws ParseException {
        Integer dateInteger = DateUtils.formatDate4(DateUtils.getBeforeDay(DateUtils.formatStrDate4(date)));
        // 获取所有有网站域名的学校
        List<SwsSettingDomains> domainsList = domainsRepository.findByDomainNameIsNotNull();

        // 去掉重复的数据:久平台一个学校可以设置多个域名
        Set<String> set = new HashSet<String>();
        for (SwsSettingDomains domains : domainsList) {
            String schoolId = domains.getSchoolId();
            String webUrl = domains.getDomainName();
            // schoolId不能为空
            if (StringUtils.isNotBlank(schoolId) && !"null".equals(schoolId)) {
                // 网站域名不能为空
                if (StringUtils.isNotBlank(webUrl) && !"null".equals(webUrl)) {
                    set.add(schoolId);
                }
            }
        }
        List<SchoolModel> schoolModelLst = new ArrayList<SchoolModel>();
        SchoolModel schoolModel = null;
        for (String schoolStr : set) {
            schoolModel = new SchoolModel();
            schoolModel.schoolId = schoolStr;
            schoolModel.date = dateInteger;
            schoolModelLst.add(schoolModel);
        }
        if (schoolModelLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("schoolList", schoolModelLst);
                HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/sws/schoolIdList/month/buquan/",
                        formEntity, String.class);
                if (result.contains("success")) {
                    LOGGER.info("SwsWebsiteStatisticsMGImpl.getKaiTongSchoolMonth():2.补全开通网站的学校数量(month)  成功");
                }
            } catch (Exception e) {
                String to = "1179032010@qq.com";
                String header = "补全开通网站的学校数量(month) 报错";
                String text = "SwsWebsiteStatisticsMGImpl.getKaiTongSchoolMonth()：2." + e.getMessage();
                // ## 发送邮件
                SendEmailUtil.sendEmailValidate(to, null, header, text);
                LOGGER.info("错误日志2*****:" + e.getMessage());
            }
        } else {
            LOGGER.info("###########2.没有开通网站的学校,SWS_SETTING_DOMAINS is null");
        }
    }

    /**
     * 补全学校下面的栏目
     */
    @Override
    public void getLanMuMessage(Integer date) throws ParseException {
        date = DateUtils.formatDate4(DateUtils.getBeforeDay(DateUtils.formatStrDate4(date)));
        List<SwsSectionModel> swsSectionModelLst = new ArrayList<SwsSectionModel>();
        List<SwsSection> swsSectionLst = swsSectionRepository.findByPid("0");
        for (SwsSection swsSection : swsSectionLst) {
            if (swsSection.getSectionName() == null || swsSection.getSectionName().trim() == "") continue;
            SwsSectionModel swsSectionModel = new SwsSectionModel();
            swsSectionModel.date = date;
            swsSectionModel.id = swsSection.getId().trim();
            swsSectionModel.schoolId = swsSection.getSchoolId().trim();
            swsSectionModel.sectionName = swsSection.getSectionName().trim();
            swsSectionModelLst.add(swsSectionModel);
        }
        if (swsSectionModelLst.size() > 0) {
            Integer index = 0;
            List<SwsSectionModel> lanmulist = new ArrayList<>();
            for (SwsSectionModel s : swsSectionModelLst) {
                lanmulist.add(s);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("swsSectionModelLst", lanmulist);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(
                                yxyApiYxUrl + "/comm/school/sws/section/article/sav/", formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuMessage():4.补全学校下面的栏目 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "补全学校下面的栏目 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getLanMuMessage()：4." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志4******:" + e.getMessage());
                    }
                    lanmulist = new ArrayList<>();
                    index = 0;
                }
            }
            if (lanmulist.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("swsSectionModelLst", lanmulist);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/sws/section/article/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuMessage():4.补全学校下面的栏目 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "补全学校下面的栏目 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getLanMuMessage()：4." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志4******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("##############4.栏目表为空,SWS_SECTION is null");
        }
    }

    /*
     * 网站每日pv统计yxy.statistics.busi.sws.pv.day
     * 数据来源sws_article_daily_analyze(网站点击量 栏目点击量) 数据来源="yxy.sws.article(资讯数量)
     * 
     * @see
     * com.china08.yxyapi.service.sws.sws.SwsWebsiteStatisticsMG#getZiXunCount(
     * java.lang.Integer)
     */
    @Override
    public void getZiXunCount(Integer date) throws ParseException {
        date = DateUtils.formatDate4(DateUtils.getBeforeDay(DateUtils.formatStrDate4(date)));
        TypedAggregation<SwsPvForDailyAnalyze> aggregationZong = Aggregation.newAggregation(SwsPvForDailyAnalyze.class,
                Aggregation.match(Criteria.where("yearForPv").is(DateUtils.year(DateUtils.formatStrDate4(date)))
                        .and("monthForPv").is(DateUtils.month(DateUtils.formatStrDate4(date))).and("dayForPv")
                        .is(DateUtils.date(DateUtils.formatStrDate4(date)))),
                Aggregation.group("schoolId").sum("pv").as("pv").first("schoolId").as("schoolId"));
        AggregationResults<PvForDaily> resultZong = mongoTemplate.aggregate(aggregationZong, PvForDaily.class);
        List<PvForDaily> dateModelLst = resultZong.getMappedResults();

        // --------------------------------以上是访问统计量------------------------------------------

        TypedAggregation<SwsArticleForDailyAnalyze> swsaggregationZong = Aggregation.newAggregation(
                SwsArticleForDailyAnalyze.class,
                Aggregation.match(Criteria.where("yearForPv").is(DateUtils.year(DateUtils.formatStrDate4(date)))
                        .and("monthForPv").is(DateUtils.month(DateUtils.formatStrDate4(date))).and("dayForPv")
                        .is(DateUtils.date(DateUtils.formatStrDate4(date)))),
                Aggregation.group("schoolId").sum("pv").as("pv").first("schoolId").as("schoolId"));
        AggregationResults<SwsArticleForDaily> swsresultZong = mongoTemplate.aggregate(swsaggregationZong,
                SwsArticleForDaily.class);
        List<SwsArticleForDaily> swsresultLst = swsresultZong.getMappedResults();

        // -----------------------------------------以上栏目的点击量(从文章的点击量统计过来)-----------------------------------------------//

        TypedAggregation<SwsArticle> wenzhangZong = Aggregation.newAggregation(SwsArticle.class,
                Aggregation
                        .match(Criteria.where("publishDate").gte(DateUtils.getFirstDay(DateUtils.formatStrDate4(date)))
                                .lte(DateUtils.getTimesnight(DateUtils.formatStrDate4(date)))),
                Aggregation.group("ownerSchoolId").count().as("pv").first("ownerSchoolId").as("schoolId"));
        AggregationResults<ArticleDaily> resultWenzhangZong = mongoTemplate.aggregate(wenzhangZong, ArticleDaily.class);
        List<ArticleDaily> resultWenzhangLst = resultWenzhangZong.getMappedResults();
        // ---------------------------------------------以上为文章统计数量-------------------------------------------------------//
        if (resultWenzhangLst != null && resultWenzhangLst.size() > 0) {
            List<ArticleDaily> articlelist = new ArrayList<>();
            Integer index = 0;
            for (ArticleDaily articleDaily : resultWenzhangLst) {
                articleDaily.date = date;
                articlelist.add(articleDaily);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("resultWenzhangLst", articlelist);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swspv/wenzhang/sav/",
                                formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():5.网站每日pv统计(文章统计数量) 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "网站每日pv统计(文章统计数量) 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：5." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志5******:" + e.getMessage());
                    }
                    articlelist = new ArrayList<>();
                    index = 0;
                }
            }
            if (articlelist.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("resultWenzhangLst", articlelist);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swspv/wenzhang/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():5.网站每日pv统计(文章统计数量) 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "网站每日pv统计(文章统计数量) 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：5." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志5******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("##############5.yxy.sws.article中" + date + "资讯发布量为空");
        }

        if (swsresultLst != null && swsresultLst.size() > 0) {
            List<SwsArticleForDaily> articlepvlist = new ArrayList<>();
            Integer index = 0;
            for (SwsArticleForDaily swsArticleForDaily : swsresultLst) {
                swsArticleForDaily.date = date;
                articlepvlist.add(swsArticleForDaily);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("swsresultLst", articlepvlist);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swspv/lanmudianji/sav/",
                                formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():6.网站每日pv统计(栏目的点击量) 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "网站每日pv统计(栏目的点击量) 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：6." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志6******:" + e.getMessage());
                    }
                    articlepvlist = new ArrayList<>();
                    index = 0;
                }
            }
            if (articlepvlist.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("swsresultLst", articlepvlist);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swspv/lanmudianji/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():6.网站每日pv统计(栏目的点击量) 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "网站每日pv统计(栏目的点击量) 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：6." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志6******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("##############6.sws_article_daily_analyze中" + date + "栏目pv点击量为空");
        }

        if (dateModelLst != null && dateModelLst.size() > 0) {
            List<PvForDaily> pvList = new ArrayList<>();
            Integer index = 0;
            for (PvForDaily pvForDaily : dateModelLst) {
                pvForDaily.date = date;
                pvList.add(pvForDaily);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("dateModelLst", pvList);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(
                                yxyApiYxUrl + "/comm/school/swspv/fangwentongji/sav/", formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():7.网站每日pv统计(访问统计量) 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "网站每日pv统计(访问统计量) 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：7." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志7******:" + e.getMessage());
                    }
                    pvList = new ArrayList<>();
                    index = 0;
                }
            }
            if (pvList.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("dateModelLst", pvList);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swspv/fangwentongji/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getZiXunCount():7.网站每日pv统计(访问统计量) 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "网站每日pv统计(访问统计量) 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getZiXunCount()：7." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志7******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("##############7.sws_article_daily_analyze中" + date + "网站pv点击量为空");
        }

    }

    /**
     * 统计访问栏目数量
     * 
     * @throws ParseException
     */
    @Override
    public void getLanMuCount(Integer date) throws ParseException {
        Date beforeDate = DateUtils.getBeforeDay(DateUtils.formatStrDate4(date));
        Integer beforeDateInt = DateUtils.formatDate4(beforeDate);
        Date end = DateUtils.getMothOfLastDay(beforeDate);
        TypedAggregation<SwsArticle> aggregationZong = Aggregation.newAggregation(SwsArticle.class,
                Aggregation.match(Criteria.where("publishDate").lte(end)),
                Aggregation.group("section1Id", "ownerSchoolId").count().as("articleCount").first("ownerSchoolId")
                        .as("schoolId").first("section1Id").as("section1Id"));
        AggregationResults<LanMuTwoModel> resultZong = mongoTemplate.aggregate(aggregationZong, LanMuTwoModel.class);
        List<LanMuTwoModel> lanMuModelLst = resultZong.getMappedResults();
        List<LanMuTwoModel> newschoolModelLst = new ArrayList<LanMuTwoModel>();
        // --------------------------------------以上统计的是该月之前文章数量-------------------------------------------------------------------//
        TypedAggregation<SwsArticleForDailyAnalyze> aggregationZong1 = Aggregation.newAggregation(
                SwsArticleForDailyAnalyze.class, Aggregation.match(Criteria.where("dateForPv").lte(end)),
                Aggregation.group("section1Id", "schoolId").sum("pv").as("pv").first("schoolId").as("schoolId")
                        .first("section1Id").as("section1Id"));
        AggregationResults<LanMuModel> resultZong1 = mongoTemplate.aggregate(aggregationZong1, LanMuModel.class);
        List<LanMuModel> lanMuModelLst1 = resultZong1.getMappedResults();
        List<LanMuModel> newlanMuModelLst1 = new ArrayList<>();
        // --------------------------------------以上统计的是文章该月之前浏览数量-------------------------------------------------------------------//
        if (lanMuModelLst1 != null && lanMuModelLst1.size() > 0) {
            for (LanMuModel lanMuModel : lanMuModelLst1) {
                if (lanMuModel.section1Id == null || lanMuModel.section1Id.trim().equals("")) continue;
                SwsSection swsSection = swsSectionRepository.findOne(lanMuModel.section1Id.trim());
                if (swsSection == null) continue;
                if (swsSection.getSectionName() == null || swsSection.getSectionName().trim() == "") continue;
                lanMuModel.section1Name = swsSection.getSectionName().trim();
                lanMuModel.dateForPv = beforeDateInt;
                newlanMuModelLst1.add(lanMuModel);
            }
        }
        if (newlanMuModelLst1.size() > 0) {
            List<LanMuModel> pvmonthlist = new ArrayList<>();
            Integer index = 0;
            for (LanMuModel lan : newlanMuModelLst1) {
                pvmonthlist.add(lan);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("lanMuDianJiModelLst", pvmonthlist);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swsLan/dianjiliang/sav/",
                                formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuCount():8.统计访问栏目数量(文章该月之前浏览数量) 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "统计访问栏目数量(文章该月之前浏览数量) 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getLanMuCount()：8." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志8******:" + e.getMessage());
                    }
                    pvmonthlist = new ArrayList<>();
                    index = 0;
                }
            }
            if (pvmonthlist.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("lanMuDianJiModelLst", pvmonthlist);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swsLan/dianjiliang/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuCount():8.统计访问栏目数量(文章该月之前浏览数量) 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "统计访问栏目数量(文章该月之前浏览数量) 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getLanMuCount()：8." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志8******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("############8.资讯" + end + "之前访问量为空sws_article_daily_analyze");
        }
        if (lanMuModelLst != null && lanMuModelLst.size() > 0) {
            for (LanMuTwoModel lanMuModel : lanMuModelLst) {
                if (lanMuModel.section1Id == null || lanMuModel.section1Id.trim().equals("")) continue;
                SwsSection swsSection1 = swsSectionRepository.findOne(lanMuModel.section1Id.trim());
                if (swsSection1 == null) continue;
                if (swsSection1.getSectionName() == null || swsSection1.getSectionName().trim() == "") continue;
                lanMuModel.section1Name = swsSection1.getSectionName().trim();
                lanMuModel.dateForPv = beforeDateInt;
                newschoolModelLst.add(lanMuModel);
            }
        }
        if (newschoolModelLst.size() > 0) {
            List<LanMuTwoModel> articlelist = new ArrayList<>();
            Integer index = 0;
            for (LanMuTwoModel lan : newschoolModelLst) {
                articlelist.add(lan);
                index++;
                if (index == 200) {
                    try {
                        HttpHeaders headers = new HttpHeaders();
                        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                        headers.setContentType(type);
                        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("lanMuCountModelLst", articlelist);
                        HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                        String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swsLan/count/sav/",
                                formEntity, String.class);
                        if (result.contains("success")) {
                            LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuCount():9.统计访问栏目数量(该月之前文章数量) 成功");
                        }
                    } catch (Exception e) {
                        String to = "1179032010@qq.com";
                        String header = "统计访问栏目数量(该月之前文章数量) 报错";
                        String text = "SwsWebsiteStatisticsMGImpl.getLanMuCount()：9." + e.getMessage();
                        // ## 发送邮件
                        SendEmailUtil.sendEmailValidate(to, null, header, text);
                        LOGGER.info("错误日志9******:" + e.getMessage());
                    }
                    articlelist = new ArrayList<>();
                    index = 0;
                }
            }
            if (articlelist.size() > 0) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("lanMuCountModelLst", articlelist);
                    HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(map, headers);
                    String result = restTemplate.postForObject(yxyApiYxUrl + "/comm/school/swsLan/count/sav/",
                            formEntity, String.class);
                    if (result.contains("success")) {
                        LOGGER.info("SwsWebsiteStatisticsMGImpl.getLanMuCount():9.统计访问栏目数量(该月之前文章数量) 成功");
                    }
                } catch (Exception e) {
                    String to = "1179032010@qq.com";
                    String header = "统计访问栏目数量(该月之前文章数量) 报错";
                    String text = "SwsWebsiteStatisticsMGImpl.getLanMuCount()：9." + e.getMessage();
                    // ## 发送邮件
                    SendEmailUtil.sendEmailValidate(to, null, header, text);
                    LOGGER.info("错误日志9******:" + e.getMessage());
                }
            }
        } else {
            LOGGER.info("############9.资讯" + end + "之前发布量为空sws_article_daily_analyze");
        }
    }

    class LanMuTwoModel {
        public String schoolId;
        public String section1Id;
        public String section1Name;
        public Long articleCount = 0l;
        public Integer dateForPv;
    }

    class LanMuModel {
        public String schoolId;
        public String section1Id;
        public String section1Name;
        public Long pv = 0l;
        public Integer dateForPv;
    }

    class PvForDaily {
        public Long pv;
        public String schoolId;
        public Integer date;
    }

    class SwsArticleForDaily {
        public Long pv;
        public String schoolId;
        public Integer date;
    }

    class ArticleDaily {
        public String schoolId;
        public Long pv;
        public Integer date;
    }

    class DateModel {
        public String schoolId;
        public Long pv;
    }

    class ArticleModel {
        public String schoolId;
        public Long pv = 0l;
        public Integer date;
    }

    class SchoolModel {
        public String schoolId;
        public Integer date;
    }

    class SwsSectionModel {
        // 学校id
        public String schoolId;
        // 栏目name
        public String sectionName;
        // 栏目id
        public String id;
        // 日期
        public Integer date;
    }
}
